using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rocuna.Core.Extensions;
using Rocuna.Graphics;

namespace WindowsGameLibrary1.Primitives
{
    /// <summary>
    /// BillBoradHandle component
    /// </summary>
    public class BillBoard : DrawableGameComponent
    {
        /// <summary>
        /// Creates a new instance of DrawableGameComponent.
        /// </summary>
        /// <param name="texture2D">The texture2 D.</param>
        /// <param name="game">The Game that the game component should be attached to.</param>
        public BillBoard(Texture2D texture2D, Game game)
            : base(game)
        {
            _texture = texture2D;
            Position = new Vector3(0, 45, 0);
            Size = 0.25f;
        }

        #region fields

        private SpriteBatch _spriteBatch;

        private Texture2D _texture;

        private BasicEffect _effect;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the position.
        /// </summary>
        /// <value>
        /// The position.
        /// </value>
        public Vector3 Position { get; set; }

        /// <summary>
        /// Gets or sets the size.
        /// </summary>
        /// <value>
        /// The size.
        /// </value>
        public float Size { get; set; }

        #endregion

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            _effect = new BasicEffect(Game.GraphicsDevice)
                          {
                              TextureEnabled = true,
                              VertexColorEnabled = true
                          };

            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            var camera = Game.GetService<GraphicManager>().CurrentCamera;
            var cameraFront = camera.Position - camera.Target;
            _effect.World = Matrix.CreateConstrainedBillboard(Position, Position - cameraFront, Vector3.Down, null, null);
            _effect.View = Game.GetService<GraphicManager>().CurrentCamera.View;
            _effect.Projection = Game.GetService<GraphicManager>().CurrentCamera.Projection;
            Vector2 origon = new Vector2((float)_texture.Height * Size / 2, (float)_texture.Width * Size / 2);
            _spriteBatch.Begin(0, null, null, DepthStencilState.DepthRead, RasterizerState.CullNone, _effect);
            _spriteBatch.Draw(_texture, Vector2.Zero, null, Color.White, 0, origon, Size, 0, 0);
            _spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}